<?php
class PostController extends AdminController {
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($contEdit=false) {
		$model = new Post('adminCreate');
		$model->visibility = Post::VISIBILITY_PUBLIC;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if (isset($_POST['Post'])) {
			$model->attributes = $_POST['Post'];
			if ($model->save()) {
				$this->saveTag($model);
				Yii::app()->user->setFlash('success', 'The post has been saved');
				$route = $contEdit ? array('update', 'id'=>$model->id) : array('index');
				$this->redirect($route);
			}
		}
		
		$this->render('create', array(
			'model' => $model
		));
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id, $contEdit=false) {
		$model = $this->loadModel($id);
		$model->scenario   = 'adminUpdate';
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if (isset($_POST['Post'])) {
			$model->attributes = $_POST['Post'];
			if ($model->save()) {
				$this->saveTag($model);
				Yii::app()->user->setFlash('success', 'The post has been saved');
				$route = $contEdit ? array('update', 'id'=>$model->id) : array('index');
				$this->redirect($route);
			}
		}
		
		$this->render('update', array(
			'model' => $model
		));
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		$this->loadModel($id)->delete();
		
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if (!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}
	
	/**
	 * Manages all models.
	 */
	public function actionIndex() {
		$model = new Post('search');
		$model->unsetAttributes(); // clear any default values
		if (isset($_GET['Post']))
			$model->attributes = $_GET['Post'];
		
		$this->render('index', array(
			'model' => $model
		));
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Post the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id) {
		$model = Post::model()->findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		$model->tags = $model->getSelectedTagIds();
		return $model;
	}
	
	public function saveTag($model) {
		if (!is_array($model->tags)) return;
		
		PostTag::model()->deleteAll("post_id={$model->id}");
		foreach($model->tags as $tId) {
			$pt = new PostTag();
			$pt->post_id = $model->id;
			$pt->tag_id = $tId;
			$pt->save();
		}
	}
	
	/**
	 * Performs the AJAX validation.
	 * @param Post $model the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'post-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionMassActions() {
		if (!Yii::app()->request->isPostRequest)
			throw new CHttpException(404, 'The requested page could not be found');
			
		$action = $_POST['action'];
		
		switch($action) {
			case 'update':
				$this->redirect(array('massUpdate', 'ids'=>$_POST['items']));
				break;
			case 'delete':
				$this->redirect(array('massDelete', 'ids'=>$_POST['items']));
				break;
			default:
				throw new CHttpException(400, 'The request cannot be fulfilled due to bad syntax'); 
		}		
	}
	
	public function actionMassUpdate($ids) {
		$model = new MassUpdateForm();
		$model->post_ids = $ids;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if (isset($_POST['MassUpdateForm'])) {
			$model->attributes = $_POST['MassUpdateForm'];
			$affected = $model->save();
			Yii::app()->user->setFlash('success', "$affected posts has been saved");
			$this->redirect(array('index'));
		}
		
		$this->render('massUpdate', array(
			'model' => $model
		));
	}
	
	public function actionMassDelete($ids) {
		$ids = str_replace('_', ',', $ids);
		if (Yii::app()->request->isPostRequest) {
			$affected = Post::model()->deleteAll("id IN ($ids)");
			Yii::app()->user->setFlash('success', "$affected posts has been deleted");
			$this->redirect(array('index'));
		}
		
		$models = Post::model()->findAll("id IN ($ids)");
		$this->render('massDelete', array(
			'models' => $models
		));
	}
}
